//
//  GMPopGMNoteVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/11/5.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMPopGMNoteVC.h"
#import "GMTextView.h"
#import "GMAudioView.h"
#import "GMPhotoCell.h"
#import "TZImagePickerController.h"
#import <KSPhotoBrowser/KSPhotoBrowser.h>
#import "GMFileModel.h"
#import "RecordHUD.h"
#import "D3RecordButton.h"
#import "GMChoseFileVC.h"
@interface GMPopGMNoteVC ()<UICollectionViewDataSource,UICollectionViewDelegate,XMGWaterflowLayoutDelegate,TZImagePickerControllerDelegate,D3RecordDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scollview;
@property (weak, nonatomic) IBOutlet UIView *bagView;
@property (weak, nonatomic) IBOutlet UIButton *remeberBtn;
@property (weak, nonatomic) IBOutlet UIButton *changeBtn;
@property (weak, nonatomic) IBOutlet D3RecordButton *btn;
@property (nonatomic, strong) UICollectionView *collectionView;
/**本地图片数组*/
@property (nonatomic, strong) NSMutableArray *imgArr;
@property(nonatomic,assign)NSInteger maxCount;//最多个数
/**上传到服务器的图片模型数组*/
@property (nonatomic, strong) NSMutableArray *netImgArr;
/**本地语音*/
@property (nonatomic, strong) NSMutableArray *audioArr;
/**上传到服务器的语音数组*/
@property (nonatomic, strong) NSMutableArray *netaudioArr;
@property (nonatomic, strong) GMTextView *textView;
@property (nonatomic, strong) GMAudioView *audioView;
@property (nonatomic, assign) BOOL isAudio;
@property (nonatomic, assign) BOOL isSelected;
@property (nonatomic, copy) NSString *ishare;

@end

@implementation GMPopGMNoteVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.remeberBtn.selected =YES;
    self.maxCount = 5;/**设置最大图片数量*/
    self.scollview.scrollEnabled = false;
    self.scollview.contentSize = CGSizeMake(DEVICE_WIDTH*2, 0);
    [self.scollview addSubview:self.textView];
    [self.scollview addSubview:self.audioView];
    [self.collectionView registerNib:[UINib nibWithNibName:@"GMPhotoCell" bundle:nil] forCellWithReuseIdentifier:@"GMPhotoCell"];
    /**限制最多录入两分钟*/
    [_btn initRecord:self maxtime:120 title:@"上滑取消录音"];
    self.btn.hidden = YES;
    self.ishare = @"true";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updataBtnSatate) name:@"updataBtn" object:nil];
}
-(void)endRecord:(NSData *)voiceData{
    [self.audioArr addObject:voiceData];
    self.audioView.dataArr = self.audioArr;
    if (self.audioArr.count >2) {
        self.btn.backgroundColor = kDarkGrayColor;
        [self.btn setTitle:@"限制录制三段语音" forState:UIControlStateNormal];
        self.btn.userInteractionEnabled = NO;
    }else{
        self.btn.backgroundColor = [UIColor colorWithHexString:@"007AFF"];
        [self.btn setTitle:@"长按录音" forState:UIControlStateNormal];
        self.btn.userInteractionEnabled = YES;
    }
}
-(void)updataBtnSatate{
    self.btn.backgroundColor = [UIColor colorWithHexString:@"007AFF"];
    [self.btn setTitle:@"长按录音" forState:UIControlStateNormal];
    self.btn.userInteractionEnabled = YES;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        //1.初始化layout
        // 创建布局
        XMGWaterflowLayout *layout = [[XMGWaterflowLayout alloc] init];
        layout.delegate = self;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH-30, 80) collectionViewLayout:layout];
        _collectionView.backgroundColor = kWhiteColor;
        _collectionView.dataSource = self;
        _collectionView.scrollEnabled = NO;
        _collectionView.delegate = self;
        [self.bagView addSubview:_collectionView];
        
    }
    return _collectionView;
}
-(NSMutableArray *)netaudioArr{
    if (!_netaudioArr) {
        _netaudioArr = [[NSMutableArray alloc] init];
    }
    return _netaudioArr;
}
-(NSMutableArray *)audioArr{
    if (!_audioArr) {
        _audioArr = [[NSMutableArray alloc] init];
    }
    return _audioArr;
}
-(NSMutableArray *)netImgArr{
    if (!_netImgArr) {
        _netImgArr = [[NSMutableArray alloc] init];
    }
    return _netImgArr;
}
-(NSMutableArray *)imgArr{
    if (!_imgArr) {
        _imgArr = [[NSMutableArray alloc] init];
    }
    return _imgArr;
}
-(GMTextView *)textView{
    if (!_textView) {
        _textView = [GMTextView viewFromXib];
        _textView.isNotStar = YES;
        _textView.frame = CGRectMake(0, 0, DEVICE_WIDTH, 130);
        _textView.tempStr = @"笔记内容至少4个字";
    }
    return _textView;
}
-(GMAudioView *)audioView{
    if (!_audioView) {
        _audioView = [GMAudioView viewFromXib];
        _audioView.frame = CGRectMake(DEVICE_WIDTH, 0, DEVICE_WIDTH, 130);
    }
    return _audioView;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imgArr.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMPhotoCell" forIndexPath:indexPath];
    if (indexPath.row == self.imgArr.count || self.imgArr.count == 0) {
        cell.photoImg.image = [UIImage imageNamed:@"photo_add"];
        cell.delectBtn.hidden=YES;
    }else{
        NSDictionary *dict = self.imgArr[indexPath.row];
        NSString *name =[dict objectForKey:@"name"];
        if (kIsEmptyString(name)) {
             cell.photoImg.image = [dict objectForKey:@"image"];
        }else{
             cell.photoImg.image =[UIImage imageNamed:[dict objectForKey:@"image"]];
        }
        cell.delectBtn.hidden=NO;
        cell.delectBtn.tag = indexPath.row +1000;
        [cell.delectBtn addTarget:self action:@selector(delectImageWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}
#pragma mark - <XMGWaterflowLayoutDelegate>
- (CGFloat)waterflowLayout:(XMGWaterflowLayout *)waterflowLayout heightForItemAtIndex:(NSUInteger)index itemWidth:(CGFloat)itemWidth{
    //计算item的高度
    return itemWidth;
}

- (CGFloat)rowMarginInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return 10;
}
/**返回每行的个数*/
- (CGFloat)columnCountInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return 5;
}

- (UIEdgeInsets)edgeInsetsInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    kWeakObject(self)
    if (indexPath.row == self.imgArr.count) {
        
        //显示弹出框列表选择
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                       message:nil
                                                                preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 //响应事件
                                                                 NSLog(@"action = %@", action);
                                                             }];
        UIAlertAction* manAction = [UIAlertAction actionWithTitle:@"选择文件" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              GMChoseFileVC *chose = [[GMChoseFileVC alloc] init];
                                                              chose.GMChoseFileVCBlock = ^(NSDictionary *dict) {
                                                                  [weakself.imgArr addObject:dict];
                                                                  [weakself.collectionView reloadData];
                                                              };
                                                              [self presentViewController:chose animated:YES completion:nil];
                                                          }];
        UIAlertAction* womanAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction * action) {
                                                                //响应事件
                                                                TZImagePickerController *pickerController = [[TZImagePickerController alloc]initWithMaxImagesCount:self.maxCount - self.imgArr.count delegate:self];
                                                                pickerController.sortAscendingByModificationDate = NO;
                                                                pickerController.showPhotoCannotSelectLayer = YES;
                                                                kWeakObject(self)
                                                                [pickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photo, NSArray *assets, BOOL isSelectOriginalPhoto){
                                                                    
                                                                    if (photo.count) {
                                                                        [weakself addNewImages:photo];
                                                                    }
                                                                }];
                                                                [self presentViewController:pickerController animated:YES completion:nil];
                                                            }];
        [alert addAction:cancelAction];
        [alert addAction:manAction];
        [alert addAction:womanAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
}
//添加多张图片--
-(void)addNewImages:(NSArray *)newImages{
    
    //默认多张图片选择顺序是按照用户选择顺序，所以这里进行反序，因为后面把刚添加的index 置为0；
    NSArray* images = [[newImages reverseObjectEnumerator] allObjects];
    [images enumerateObjectsUsingBlock:^(UIImage * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *imgDict = @{@"image":obj};
        [self.imgArr insertObject:imgDict atIndex:0];
        
    }];
    [self.collectionView reloadData];
    //先从服务器获取OSS需要的数据
    
}
- (void)delectImageWithBtn:(UIButton *)sender{
    NSInteger index =sender.tag -1000;
    [self.imgArr removeObjectAtIndex:index];
    [self.collectionView reloadData];
}
- (IBAction)changeBtnClick:(id)sender {
    if (self.isAudio) {
        self.btn.hidden = YES;
        self.scollview.contentOffset = CGPointMake(0, 0);
        [self.changeBtn setImage:[UIImage imageNamed:@"microphone-gray"] forState:UIControlStateNormal];
    }else{
        self.btn.hidden = NO;
        self.scollview.contentOffset = CGPointMake(DEVICE_WIDTH, 0);
        [self.changeBtn setImage:[UIImage imageNamed:@"keyboard"] forState:UIControlStateNormal];
    }
    _isAudio = !_isAudio;
}
- (IBAction)closePopView:(id)sender {
    UIViewController * parent = [self.view containingViewController];
    if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
        [parent dismissSemiModalView];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoPlay" object:nil];
}
- (IBAction)sumbitNote:(id)sender {
    [MBProgressHUD showErrorOrSuc:@"提交中" toView:self.view];
    dispatch_group_t uploadGroup = dispatch_group_create();
    for (NSInteger i =0; i<self.audioArr.count; i++) {
        dispatch_group_enter(uploadGroup);
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"fileType":@"res-note"
                              };
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.mp3", dateString];
        [HJNetwork uploadImageURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UploadFile&$v=%@",VERSION] parameters:dict imageData:self.audioArr[i] name:@"audio_file" fileName:fileName mimeType:@"audio/mpeg" progress:^(NSProgress *progress) {
            
        } callback:^(id responseObject, NSError *error) {
            if (!error) {
                if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]){
                    GMFileModel *model = [GMFileModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                    [self.netaudioArr addObject:model];
                    dispatch_group_leave(uploadGroup);
                }else{
                    /**显示错误信息*/
                    [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
                }
            }
        }];
    }
    for (NSInteger i =0; i<self.imgArr.count; i++) {
        dispatch_group_enter(uploadGroup);
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"fileType":@"res-note"
                              };
        NSDictionary *temDict = self.imgArr[i];
        NSString *name =[temDict objectForKey:@"name"];
        UIImage *tempImg;
        if (kIsEmptyString(name)) {
            //上传图片
            tempImg = [temDict objectForKey:@"image"];
            NSData *imageData = UIImageJPEGRepresentation(tempImg, 0.5);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
            [HJNetwork uploadImageURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UploadFile&$v=%@",VERSION] parameters:dict imageData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg" progress:^(NSProgress *progress) {
                
            } callback:^(id responseObject, NSError *error) {
                if (!error) {
                    if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]){
                        GMFileModel *model = [GMFileModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                        [self.netImgArr addObject:model];
                        dispatch_group_leave(uploadGroup);
                    }else{
                        /**显示错误信息*/
                        [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
                    }
                }
            }];
        }else{
            //上传文件
            NSString *filePath = [temDict objectForKey:@"path"];
            NSData *fileData = [NSData dataWithContentsOfFile:filePath];
            NSString *fileName = [temDict objectForKey:@"name"];
            NSString *mimeType = @"";
            if ([fileName containsString:@"zip"]) {
                mimeType =@"application/zip";
            }else if ([fileName containsString:@"pdf"]) {
                mimeType =@"application/pdf";
            }else if ([fileName containsString:@"ppt"]) {
                mimeType =@"application/vnd.ms-powerpoint";
            }else if ([fileName containsString:@"doc"]) {
                mimeType =@"application/msword";
            }else if ([fileName containsString:@"excel"]) {
                mimeType =@"application/vnd.ms-excel";
            }else if ([fileName containsString:@"rar"]) {
                mimeType =@"application/x-rar-compressed";
            }else{
                mimeType =@"text/plain";
            }
            [HJNetwork uploadImageURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UploadFile&$v=%@",VERSION] parameters:dict imageData:fileData name:@"file" fileName:fileName mimeType:mimeType progress:^(NSProgress *progress) {
                
            } callback:^(id responseObject, NSError *error) {
                if (!error) {
                    if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]){
                        GMFileModel *model = [GMFileModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                        [self.netImgArr addObject:model];
                        dispatch_group_leave(uploadGroup);
                    }else{
                        /**显示错误信息*/
                        [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
                    }
                }
            }];
        }
    }
    dispatch_group_notify(uploadGroup, dispatch_get_main_queue(), ^{
        [self sumbitAllData];
    });
}

- (IBAction)remeberBtnClick:(id)sender {
    if (_isSelected) {
        self.remeberBtn.selected =YES;
        self.ishare = @"true";
    }else{
        self.remeberBtn.selected =NO;
        self.ishare = @"false";
    }
    _isSelected = !_isSelected;
}
-(void)sumbitAllData{
    NSString *imgFile1Id =@"";
    NSString *imgFile2Id =@"";
    NSString *imgFile3Id =@"";
    NSString *imgFile4Id =@"";
    NSString *imgFile5Id =@"";
    for (NSInteger i=0; i<self.netImgArr.count; i++) {
        GMFileModel *model =self.netImgArr[i];
        switch (i) {
            case 0:{
                imgFile1Id =model.Id;
            }
                break;
            case 1:{
                imgFile2Id =model.Id;
            }
                break;
            case 2:{
                imgFile3Id =model.Id;
            }
                break;
            case 3:{
                imgFile4Id =model.Id;
            }
                break;
            case 4:{
                imgFile5Id =model.Id;
            }
                break;
                
            default:
                break;
        }
    }
    NSString *voice1Id =@"";
    NSString *voice2Id=@"";
    NSString *voice3Id =@"";
    for (NSInteger i=0; i<self.netaudioArr.count; i++) {
        GMFileModel *model =self.netaudioArr[i];
        switch (i) {
            case 0:{
                voice1Id =model.Id;
            }
                break;
            case 1:{
                voice2Id =model.Id;
            }
                break;
            case 2:{
                voice3Id =model.Id;
            }
                break;
            default:
                break;
        }
    }
    
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"resId":self.resId,
                          @"content":self.textView.textView.text?self.textView.textView.text:@"",
                          @"imgFile1Id":imgFile1Id,
                          @"imgFile2Id":imgFile2Id,
                          @"imgFile3Id":imgFile3Id,
                          @"imgFile4Id":imgFile4Id,
                          @"imgFile5Id":imgFile5Id,
                          @"voice1Id":voice1Id,
                          @"voice2Id":voice2Id,
                          @"voice3Id":voice3Id,
                          @"playPos":self.timeLenth,
                          @"isShare":self.ishare
                          };
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostResNote&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [MBProgressHUD showErrorOrSuc:@"记录成功" toView:self.view];
                /*延迟执行时间2秒*/
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    /**发送通知刷新问题页面*/
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updataNote" object:nil];
                    UIViewController * parent = [self.view containingViewController];
                    if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
                        [parent dismissSemiModalView];
                    }
                });
                [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoPlay" object:nil];
            }else{
                 [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络出错" toView:self.view];
        }
    }];
}
-(void)dealloc{
    /**页面销毁的时候移除通知*/
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"updataBtn" object:nil];
}
@end
